<script setup>
import { reactive, ref } from 'vue'
import { getChannelList, addChannel, getChannelInfo, editChannel, getQrcode } from '@/api/channel'
import { formatTime } from '@/utils'

// 查询表单数据
const form = reactive({
  code: '',
  name: '',
  status: '',
  page: 1,
  size: 10,
})

// 弹窗标题
const dialogTitle = ref('新增渠道')
// 控制弹窗显示隐藏
const dialogFormVisible = ref(false)
// 二维码弹窗控制
const qrcodeDialogVisible = ref(false)
// 二维码数据
const qrcodeData = ref({
  qrcode_url: '',
})
// 表格数据
const tableData = ref([])
// 表格loading
const tableLoading = ref(false)
// 分页总数
const total = ref(0)

// 表单校验规则
const rules = {
  code: [
    { required: true, message: '请输入渠道编号', trigger: 'blur' },
    { min: 2, max: 20, message: '渠道编号长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入渠道名称', trigger: 'blur' },
    { min: 2, max: 50, message: '渠道名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择渠道状态', trigger: 'change' }],
  describe: [
    { required: true, message: '请输入渠道说明', trigger: 'blur' },
    { min: 1, max: 200, message: '渠道说明长度在 1 到 200 个字符', trigger: 'blur' },
  ],
  manager_name: [
    { required: true, message: '请输入渠道负责人', trigger: 'blur' },
    { min: 2, max: 20, message: '渠道负责人长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  manager_phone: [
    { required: true, message: '请输入负责人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
}

// 表单ref
const addFormRef = ref()

// 获取渠道列表（带loading和分页）
const fetchChannelList = async () => {
  tableLoading.value = true
  try {
    const params = {
      code: form.code,
      name: form.name,
      status: form.status,
      page: form.page,
      page_size: form.size,
    }
    const res = await getChannelList(params)
    tableData.value = res.data.list || []
    total.value = res.data.total || 0
  } finally {
    tableLoading.value = false
  }
}

// 分页-每页条数变化
const handleSizeChange = (val) => {
  form.size = val
  fetchChannelList()
}
// 分页-页码变化
const handleCurrentChange = (val) => {
  form.page = val
  fetchChannelList()
}

// 新增/编辑弹窗表单数据
const addForm = reactive({
  id: '',
  code: '',
  name: '',
  status: '1',
  describe: '',
  manager_name: '',
  manager_phone: '',
})

// 重置弹窗表单
const resetAddForm = () => {
  addForm.id = ''
  addForm.code = ''
  addForm.name = ''
  addForm.status = '1'
  addForm.describe = ''
  addForm.manager_name = ''
  addForm.manager_phone = ''
  // 清除表单校验
  if (addFormRef.value) {
    addFormRef.value.clearValidate()
  }
}

// 新增渠道提交
const handleAdd = async () => {
  try {
    await addChannel({
      code: addForm.code,
      name: addForm.name,
      status: addForm.status,
      describe: addForm.describe,
      manager_name: addForm.manager_name,
      manager_phone: addForm.manager_phone,
    })
    dialogFormVisible.value = false
    resetAddForm()
    fetchChannelList()
  } catch (e) {}
}

// 打开新增弹窗
const add = () => {
  resetAddForm()
  dialogTitle.value = '新增渠道'
  dialogMode.value = 'add'
  dialogFormVisible.value = true
}

// 弹窗模式：add 新增，view 查看，edit 编辑
const dialogMode = ref('add')

// 查看渠道详情（只读弹窗）
const handleView = async (row) => {
  dialogMode.value = 'view'
  dialogTitle.value = '查看渠道'
  dialogFormVisible.value = true
  const res = await getChannelInfo({ id: row.id })
  const info = res.data || {}
  addForm.code = info.code || ''
  addForm.name = info.name || ''
  addForm.status = info.status ? String(info.status) : '1'
  addForm.describe = info.describe || ''
  addForm.manager_name = info.manager_name || ''
  addForm.manager_phone = info.manager_phone || ''
}

// 编辑渠道（弹窗带回显）
const handleEdit = async (row) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑渠道'
  dialogFormVisible.value = true
  const res = await getChannelInfo({ id: row.id })
  const info = res.data || {}
  addForm.id = info.id || row.id
  addForm.code = info.code || ''
  addForm.name = info.name || ''
  addForm.status = info.status ? String(info.status) : '1'
  addForm.describe = info.describe || ''
  addForm.manager_name = info.manager_name || ''
  addForm.manager_phone = info.manager_phone || ''
}

// 编辑渠道提交
const handleEditSubmit = async () => {
  try {
    await editChannel({
      id: addForm.id,
      code: addForm.code,
      name: addForm.name,
      status: addForm.status,
      describe: addForm.describe,
      manager_name: addForm.manager_name,
      manager_phone: addForm.manager_phone,
      reason: '更新说明',
    })
    dialogFormVisible.value = false
    fetchChannelList()
  } catch (e) {}
}

// 弹窗保存按钮（区分新增/编辑）
const handleSave = async () => {
  // 表单校验
  if (!addFormRef.value) return

  try {
    await addFormRef.value.validate()

    if (dialogMode.value === 'add') {
      await handleAdd()
    } else if (dialogMode.value === 'edit') {
      await handleEditSubmit()
    }
  } catch (error) {
    console.log('表单校验失败:', error)
  }
}

// 切换渠道状态（启用/停用）
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 2 : 1
  try {
    await editChannel({
      id: row.id,
      code: row.code,
      name: row.name,
      status: newStatus,
      describe: row.describe,
      manager_name: row.manager_name,
      manager_phone: row.manager_phone,
      reason: '状态切换',
    })
    fetchChannelList()
  } catch (e) {}
}

// 重置查询表单
const resetForm = () => {
  form.code = ''
  form.name = ''
  form.status = ''
  form.page = 1
  form.size = 10
  fetchChannelList()
}

// 生成二维码
const handleGenerateQrcode = async (row) => {
  try {
    console.log('生成二维码，传入ID:', row.id)
    const res = await getQrcode({ id: row.id })
    console.log('二维码接口返回:', res)

    // 先测试弹窗是否能正常显示
    qrcodeDialogVisible.value = true
    console.log('弹窗状态:', qrcodeDialogVisible.value)

    // 根据实际返回的数据结构获取二维码URL
    if (res.code === 200) {
      qrcodeData.value.qrcode_url = res.data.qrcode_url
      console.log('二维码URL:', qrcodeData.value.qrcode_url)
    } else {
      console.log('接口返回异常:', res)
    }
  } catch (e) {
    console.error('生成二维码失败:', e)
  }
}

// 下载二维码
const handleDownloadQrcode = async () => {
  if (!qrcodeData.value.qrcode_url) return

  try {
    console.log('开始下载二维码...')

    // 方法1：使用fetch + blob下载
    const response = await fetch(qrcodeData.value.qrcode_url)
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`)
    }

    const blob = await response.blob()
    console.log('获取到blob数据:', blob.size, 'bytes')

    // 创建下载链接
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `二维码_${Date.now()}.jpg`

    // 确保链接不可见但可点击
    link.style.position = 'fixed'
    link.style.top = '-1000px'
    link.style.left = '-1000px'
    link.style.opacity = '0'
    link.style.pointerEvents = 'none'

    document.body.appendChild(link)

    // 模拟用户点击
    const clickEvent = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    })

    link.dispatchEvent(clickEvent)
    console.log('触发下载点击事件')

    // 清理
    setTimeout(() => {
      URL.revokeObjectURL(url)
      if (link.parentNode) {
        document.body.removeChild(link)
      }
      console.log('下载链接已清理')
    }, 1000)
  } catch (error) {
    console.error('fetch下载失败:', error)

    // 备用方案：直接创建下载链接
    try {
      const link = document.createElement('a')
      link.href = qrcodeData.value.qrcode_url
      link.download = `二维码_${Date.now()}.jpg`
      link.target = '_blank'
      link.rel = 'noopener noreferrer'

      link.style.position = 'fixed'
      link.style.top = '-1000px'
      link.style.left = '-1000px'

      document.body.appendChild(link)
      link.click()

      setTimeout(() => {
        if (link.parentNode) {
          document.body.removeChild(link)
        }
      }, 1000)

      console.log('使用备用下载方案')
    } catch (linkError) {
      console.error('备用下载也失败:', linkError)

      // 最后的方案：提示用户手动下载
      if (confirm('自动下载失败，是否在新窗口打开图片进行手动下载？')) {
        window.open(qrcodeData.value.qrcode_url, '_blank')
      }
    }
  }
}

// 页面加载自动查询
fetchChannelList()
</script>

<template>
  <div>
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="渠道编号:">
        <el-input v-model="form.code" placeholder="请输入渠道编号" clearable style="width: 185px" />
      </el-form-item>
      <el-form-item label="渠道名称:">
        <el-input v-model="form.name" placeholder="请输入渠道名称" clearable style="width: 185px" />
      </el-form-item>
      <el-form-item label="渠道状态:">
        <el-select
          v-model="form.status"
          placeholder="请选择渠道状态"
          clearable
          style="width: 185px"
        >
          <el-option label="开启" :value="1" />
          <el-option label="停用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchChannelList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetForm" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <div class="actions-btn">
      <el-button type="primary" @click="add">新增</el-button>
    </div>
    <el-table
      :data="tableData"
      v-loading="tableLoading"
      border
      style="height: calc(100vh - 350px)"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="渠道编号" width="180">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleView(row)" class="code-link-btn">
            {{ row.code }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="渠道名称" width="200" />
      <!-- <el-table-column prop="name" label="渠道说明" width="220" /> -->
      <el-table-column label="渠道状态" width="200">
        <template #default="{ row }">
          <el-button
            class="code-link-btn"
            link
            :type="row.status === 1 ? 'success' : 'danger'"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '开启' : '停用' }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="describe" label="渠道说明" width="250" />
      <el-table-column prop="manager_name" label="渠道负责人" width="150">
        <template #default="{ row }">
          <span>{{ row.manager_name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager_phone" label="负责人电话" width="150">
        <template #default="{ row }">
          <span>{{ row.manager_phone || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updated_at" label="更新时间" width="280">
        <template #default="scope">
          <span>{{ scope.row.updated_at ? formatTime(scope.row.updated_at) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="更新说明" width="150" />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <el-button
            link
            type="success"
            size="small"
            @click="handleGenerateQrcode(row)"
            class="code-link-btn"
          >
            生成二维码
          </el-button>
          <el-button link type="primary" size="small" @click="handleView(row)" class="code-link-btn"
            >查看</el-button
          >
          <el-button link type="danger" size="small" @click="handleEdit(row)" class="code-link-btn"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="form.size"
        :current-page="form.page"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
      <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="100">
        <el-form-item label="渠道编号" prop="code">
          <el-input
            v-model="addForm.code"
            autocomplete="off"
            placeholder="请输入渠道编号"
            style="width: 200px"
            v-if="dialogMode !== 'view'"
          />
          <span v-else>{{ addForm.code }}</span>
        </el-form-item>
        <el-form-item label="渠道名称" prop="name">
          <el-input
            v-model="addForm.name"
            autocomplete="off"
            placeholder="请输入渠道名称"
            style="width: 200px"
            v-if="dialogMode !== 'view'"
          />
          <span v-else>{{ addForm.name }}</span>
        </el-form-item>
        <el-form-item label="渠道负责人" prop="manager_name">
          <el-input
            v-model="addForm.manager_name"
            autocomplete="off"
            placeholder="请输入渠道负责人"
            style="width: 200px"
            v-if="dialogMode !== 'view'"
          />
          <span v-else>{{ addForm.manager_name }}</span>
        </el-form-item>
        <el-form-item label="负责人电话" prop="manager_phone">
          <el-input
            v-model="addForm.manager_phone"
            autocomplete="off"
            placeholder="请输入负责人电话"
            style="width: 200px"
            v-if="dialogMode !== 'view'"
          />
          <span v-else>{{ addForm.manager_phone }}</span>
        </el-form-item>
        <el-form-item label="渠道状态" prop="status">
          <el-radio-group v-model="addForm.status" v-if="dialogMode !== 'view'">
            <el-radio value="1" size="large">开启</el-radio>
            <el-radio value="2" size="large">停用</el-radio>
          </el-radio-group>
          <span v-else>{{ addForm.status == 1 ? '开启' : '停用' }}</span>
        </el-form-item>
        <el-form-item label="渠道说明" prop="describe">
          <el-input
            v-model="addForm.describe"
            autocomplete="off"
            placeholder="请输入"
            style="width: 200px"
            type="textarea"
            v-if="dialogMode !== 'view'"
          />
          <span v-else>{{ addForm.describe }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">关闭</el-button>
          <el-button v-if="dialogMode !== 'view'" type="primary" @click="handleSave">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 二维码展示弹窗 -->
    <el-dialog v-model="qrcodeDialogVisible" title="生成二维码" width="400" center>
      <div style="text-align: center">
        <img
          v-if="qrcodeData.qrcode_url"
          :src="qrcodeData.qrcode_url"
          alt="二维码"
          style="max-width: 200px; max-height: 200px"
        />
        <div v-else style="color: #999; padding: 40px 0">二维码加载中...</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="qrcodeDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDownloadQrcode">下载本地</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.actions-btn {
  margin-bottom: 20px;
}
.pagination {
  margin: 20px auto;
  display: flex;
  justify-content: center;
}
.tips {
  color: red;
  font-size: 12px;
}
.info span {
  color: #e6a23c;
}

/* 去除渠道编号按钮的焦点边框 */
.code-link-btn:focus {
  outline: none !important;
  box-shadow: none !important;
  border: none !important;
}

.code-link-btn:focus-visible {
  outline: none !important;
  box-shadow: none !important;
}

.code-link-btn {
}
</style>
